import { _decorator, Component, Node, ScrollView, TransformBit, UITransform, v2 } from 'cc';
import { Item } from './Item';
import { DynamicScrollViewLayoutBase } from './Abstract/DynamicScrollViewLayoutBase';
const { ccclass, property } = _decorator;

type Life_Loop_Func = (node: Node, itemBase: Item, view: DynamicScrollView) => void;

@ccclass('DynamicScrollView')
export class DynamicScrollView extends Component {
    @property(ScrollView)
    public readonly scrollView!: ScrollView;

    private dirty: boolean = false;

    /**界面布局 */
    private _layout!: DynamicScrollViewLayoutBase;
    public get layout(): DynamicScrollViewLayoutBase {
        return this._layout;
    }
    private set layout(value: DynamicScrollViewLayoutBase) {
        this._layout = value;
    }
    /**显示处理的结点 */
    private _displayNodes: Node[] = [];
    get displayNodes(): Node[] {
        return this._displayNodes;
    }
    /**制造结点的函数 */
    private make_node!: (itemBase: Item, view: DynamicScrollView) => Node;
    /**初始化结点的函数 */
    private init_node?: Life_Loop_Func;
    /**结点移除事件 */
    private node_removed_event?: Life_Loop_Func;
    /**删除结点的函数 */
    private remove_node?: Life_Loop_Func;

    /**结点链接的数据 */
    private itemBaseLinked: Map<number, Node> = new Map<number, Node>();

    private _inited = false;
    private _size_change = false;

    protected onLoad(): void {
        //注册结点变更事件
        this.node.on(UITransform.EventType.SIZE_CHANGED, () => {
            this._size_change = true;
        });
        this.scrollView.content?.on(Node.EventType.TRANSFORM_CHANGED, (type: TransformBit) => {
            if (Node.TransformBit.POSITION & (type as number)) {
                this.needUpdate();
            }
        });
        this.needUpdate();
    }

    /**初始化布局 */
    init(layout: DynamicScrollViewLayoutBase,
        make_node: (itemBase: Item, view: DynamicScrollView) => Node,
        configs?: {
            init_node?: Life_Loop_Func,
            /**接管结点移除逻辑，默认是直接销毁结点 */
            remove_node?: Life_Loop_Func,
            node_removed_event?: Life_Loop_Func,
        }) {
        //先停止滚动
        this.scrollView.stopAutoScroll();
        if (this.layout) {
            this.layout.clean();
        }
        this.layout = layout;
        //初始化布局
        this.layout.init(this);

        this.make_node = make_node;
        this.init_node = configs?.init_node;
        this.remove_node = configs?.remove_node;
        this.node_removed_event = configs?.node_removed_event;

        this._inited = true;
    }

    getItemByIndex(index: number): Item | null {
        return this.layout.Get_Item_By_Index(index);
    }

    getNodeByIndex(index: number): Node | null {
        const item = this.getItemByIndex(index);
        if (item) {
            return this.itemBaseLinked.get(index) ?? null;
        }
        return null;
    }

    getItemByNode(node: Node): Item | null {
        for (const [key, value] of this.itemBaseLinked) {
            if (value === node) {
                return this.getItemByIndex(key);
            }
        }
        return null;
    }

    /**移除结点 */
    private _removeNode(node: Node, index: number) {
        const item = this.getItemByIndex(index);
        if (!item) {
            debugger;
            return;
        }
        this.node_removed_event?.(node, item, this)
        if (this.remove_node) {
            this.remove_node(node, item, this);
        } else {
            node.destroy();
        }
    }

    public destroyAllChildren() {
        this.itemBaseLinked.forEach((node, key) => {
            this._removeNode(node, key);
        });
        this.itemBaseLinked.clear();
        this._displayNodes.length = 0;
        this.needUpdate();
    }

    protected update(deltaTime: number) {
        if (!this._inited) {
            return;
        }

        if (this._size_change) {
            this._size_change = false;
            //尺寸变更事件
            this.layout.sizeChangedEvent();
        }

        if (!this.dirty) {
            return;
        }
        this.dirty = false;
        //获取需要显示的结点列表
        const nextDisplayItemNodes = this.layout.getDisplayItemList();

        const needRemove: number[] = [];
        this.itemBaseLinked.forEach((node, index) => {
            if (!nextDisplayItemNodes.find(item => item.index === index)) {
                //移除不需要显示的结点
                needRemove.push(index);
            }
        });
        //移除不需要显示的结点
        needRemove.forEach((index) => {
            const node = this.itemBaseLinked.get(index)!;
            this._removeNode(node, index);
            this.itemBaseLinked.delete(index);
            this._displayNodes.splice(this._displayNodes.indexOf(node), 1);
        });

        //添加需要显示的结点
        nextDisplayItemNodes.forEach((itemBase) => {
            if (!this.itemBaseLinked.has(itemBase.index)) {
                //添加需要显示的结点
                const node = this.make_node(itemBase, this);
                node.name = `itemBase_${itemBase.index}`;
                node.parent = this.scrollView.content!;
                node.setPosition(itemBase.rect.x, itemBase.rect.y, 0);
                this.itemBaseLinked.set(itemBase.index, node);
                this._displayNodes.push(node);
                this.init_node?.(node, itemBase, this);
            }
        });
    }

    needUpdate() {
        this.dirty = true;
    }
}


